//
//  UIImage+YKModuleImage.m
//  YK_ExectionModel
//
//  Created by edward on 2021/4/14.
//

#import "UIImage+YKModuleImage.h"

@implementation UIImage (YKModuleImage)


+ (UIImage *)yk_moduleImage:(NSString *)bundleName className:(NSString *)className imageNamed:(NSString *)imageNamed
{
    if(imageNamed &&
       ![imageNamed isEqualToString:@""]){
        NSBundle *bundle = [NSBundle bundleForClass:NSClassFromString(className)];
        NSURL *url = [bundle URLForResource:bundleName withExtension:@"bundle"];
        if(!url) return [UIImage imageNamed:imageNamed]?:[UIImage new];
        NSBundle *imageBundle = [NSBundle bundleWithURL:url];
        
        NSString *imageName = nil;
        CGFloat scale = [UIScreen mainScreen].scale;
        if (ABS(scale-3) <= 0.001){
            imageName = [NSString stringWithFormat:@"%@@3x",imageNamed];
        }else if(ABS(scale-2) <= 0.001){
            imageName = [NSString stringWithFormat:@"%@@2x",imageNamed];
        }else{
            imageName = imageNamed;
        }
        UIImage *image = [UIImage imageWithContentsOfFile:[imageBundle pathForResource:imageName ofType:@"png"]];
        if (!image) {
            image = [UIImage imageWithContentsOfFile:[imageBundle pathForResource:imageNamed ofType:@"png"]];
            if (!image) {
                image = [UIImage imageNamed:imageNamed];
            }
        }
        return image;
    }
    
    return nil;
}

+ (UIImage *)yk_moduleXcassetImage:(NSString *)bundleName className:(NSString *)className imageNamed:(NSString *)imageNamed
{
    if(imageNamed &&
       ![imageNamed isEqualToString:@""]){
        NSBundle *bundle = [NSBundle bundleForClass:NSClassFromString(className)];
        NSURL *url = [bundle URLForResource:bundleName withExtension:@"bundle"];
        if(!url) return [UIImage imageNamed:imageNamed]?:[UIImage new];
        NSBundle *imageBundle = [NSBundle bundleWithURL:url];
        UIImage *image = [UIImage imageNamed:imageNamed inBundle:imageBundle compatibleWithTraitCollection:nil];
        return image;
    }
    
    return nil;
}

@end
